<?php

namespace Rexzy\App;

class Controller {

    public $view;
    public $request;
    public $response;

    public function __construct() {
        $this->request = \Rexzy\Http\Request::getInstance();
        $this->response = new \Rexzy\Http\Response();
        $this->view = new \Rexzy\Tool\Template('html');
        $ruleConfig = \Rexzy::getCore("ruleConfig");
        $type = $ruleConfig['type'];
        $rewrite = $ruleConfig['rewrite'];
        $host = \Rexzy::getConfig( 'url' );
        $this->view->assign( 'host', $host );
        $this->view->assign('rule_type', $type); 
    }

    /**
     *  表单验证 
     * 
     * @param type $data 要验证的表单数据
     * @param method $handleData 验证成功后数据的处理方法
     * @return boolean|string 返回验证成功或错误信息
     */
    public function formCheck($data, $handleData) {
        $error = array();
        $returnData = array();

        foreach ($data as $key => $value) {
            $inpVal = trim($value['val']);
            if (!isset($value['require'])) {
                $value['require'] = true;
            }

            if (( $value['require'] == true ) && ( $inpVal === '' )) {
                $error[$key] = array(
                    'id' => $key,
                    'result' => false,
                    'message' => $value['message']
                );
                continue;
            }

            if (( isset($value['rules']) ) && ( $inpVal !== '' )) {
                $ruleError = false;
                foreach ($value['rules'] as $key1 => $value1) {
                    if ($value1['rule']($inpVal) === false) {
                        $error[$key] = array(
                            'id' => $key,
                            'result' => false,
                            'message' => $value1['error']
                        );
                        $ruleError = true;
                        break;
                    }
                }
                if ($ruleError == true) {
                    continue;
                }
            }

            $returnData[$key] = $value['val'];
        }

        if (count($error) == 0) {
            if ($handleData($returnData) == true) {
                return array('checkWork' => true);
            } else {
                $error['otherError'] = '数据写入异常，请稍后重试';
                return $error;
            }
        } else {
            return $error;
        }

        return $error;
    }

}
